<template>
	<view class="page">
		<view class="list">
			<view>
				<view class="ss-grey-2 ss-w-90 ss-font-28 ss-m-x-30">
					<view class="list_tit ss-flex ss-p-x-10 ss-p-y-6 ss-white ss-row-between">
						<uv-notice-bar :text="text" :icon="false" bg-color="transparent" color='#fff' speed='50' />
						<view class="toDetail ss-font-27" @click="Jump">点击查看详细</view>
					</view>
				</view>
				<view class="tabBox">
					<g-tabs
						:tabs="tabList"
						:active="state.currentTab"
						key-name="buildingName"
						bg-color="transparent"
						status-bar
						:inactive-style="{
							color: '#757575',
							fontSize: '14px'
						}"
						@change="(e) => changeTab(e.index)"
					/>
				</view>
			</view>
			<uv-vtabs
				:list="state.list"
				:chain="state.chain"
				:current="currentLeft"
				bar-bg-color="#fff"
				bar-width='90'
				:offline-mode="state.offlineMode"
				:bar-style="{
					borderRight: '2rpx solid #E6F1E9',
					textAlign: 'center',
					color: '#757575',
				}"
				:bar-item-badge-style="{
					right: '10px',
					top: '19px'
				}"
				:bar-item-active-style="{
					color: '#fff',
					background: '#4EA770'
				}"
				@change="changeFloor"
			>
				<uv-vtabs-item>
					<view class="left_item">
						<view class="item-title ss-p-30">
							<view class="right" v-if="rightlist.length > 0">
								<uv-collapsePane-list
									:list="rightlist"
									:searchId="state.searchId"
									:offline-mode="state.offlineMode"
									@taskTip="taskTip"
									@fatherMethod="fatherMethod"
								/>
							</view>
						</view>
					</view>
				</uv-vtabs-item>
			</uv-vtabs>
		</view>
		<!-- 扫码 -->
		<view class="more-box">
			<view class="more-btn" :class="{ rotating: rotating }" @click="showCode">
				<uv-icon :name="state.twoCode ? 'close' : 'list'" color="#fff" size="50rpx" />
			</view>
			<view class="icon_left" :style="{
					width: state.twoCode ? '470rpx' : 0,
					opacity: state.twoCode ? 1 : 0,
				}">
				<view class="ss-m-x-40" @click="handleOffline">
					<uv-icon :name="iconOffline" size="28rpx" space="10rpx" label="任务" label-pos="bottom"
						label-size="24rpx" label-color="#212121" />
				</view>
				<view class="icon_line" />
				<view class="ss-m-x-40" @click="handleToSign">
					<uv-icon :name="iconMark" size="28rpx" space="10rpx" label="打卡" label-pos="bottom"
						label-size="24rpx" label-color="#212121" />
				</view>
				<view class="icon_line" />
				<view class="ss-m-x-40" @click="handleScan">
					<uv-icon :name="iconScan" size="28rpx" space="10rpx" label="扫码" label-pos="bottom"
						label-size="24rpx" label-color="#212121" />
				</view>
			</view>
		</view>
		<!-- 打卡提示 -->
		<view class="no-sign" v-if="noSign">
			<view class="sign-box">
				<view class="sign-top">
					<image src="../../static/card.png" />
					<uv-text text="请先完成启动打卡" color="#333333" size="32rpx" align="center" margin="30rpx 0 0" />
				</view>
				<view class="sign-bottom">
					<view class="sign-btn" @click="handleBack">返回</view>
					<view class="sign-btn" style="color: #4EA770;" @click="handleToSign">去打卡</view>
				</view>
			</view>
		</view>
		<vv-dialog v-model:projectType="state.projectType" @confirm="setUnlock" />
	</view>
</template>
<script setup>
	import {
		onMounted,
		reactive,
		ref,
		nextTick,
		onBeforeUnmount
	} from 'vue';
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app";
	import EventBus from "@/request/eventBus.js";
	import iconMark from "@/static/order/icon_mark.png";
	import iconScan from "@/static/order/icon_scan.png";
	import iconOffline from "@/static/order/icon_offline.png";
	import {
		taskSelection,
		taskSystem,
		taskIncomplete,
		isClockIn,
		unlock
	} from "@/request/task.js"
	import { checkNetwork } from "@/request/common.js";
	import vvDialog from "@/components/Dialog/Dialog.vue"

	const rightlist = ref([]);
	const noSign = ref(true); // 未打卡状态
	const tabList = ref([]) //楼栋列表
	const deviceInfo = ref({})
	const text = ref('') //滚动提示
	const fristAllow = ref(true) //第一次允许
	const currentLeft = ref(0)
	const rotating = ref(false); // 点击中
	const state = reactive({
		t: '',
		id: '',
		floorId: '',
		twoCode: false,
		currentTab: 0,
		list: [],
		chain: false,
		projectType: 0,
		searchId: "",
		count: 0,
		unlockParams: {},
		offlineMode: false,
		isOfflineTipsShow: true,
	})

	onLoad((e) => {
		uni.removeStorageSync('device-C')
		state.id = e.subPlanId
		uni.setStorageSync('subPlanId', state.id)
		state.projectType = 0
		uni.setNavigationBarTitle({
			title: `${e.projectName}第${e.cycleNo}期`
		})
	});

	onMounted(() => {
		EventBus.on("offlineChange", showFinish);
		uni.$on("listSelectStateTask", () => {
			loadDatatList()
			// 我的任务页面刷新
			uni.$emit("listStateTask");
		});
		uni.$on("network-change", (status) => {
			if (status == "none" && state.isOfflineTipsShow) {
				state.projectType = 5;
				state.isOfflineTipsShow = false;
			} else {
				state.projectType = 0;
			}
			initData();
		});
	});

	onBeforeUnmount(() => {
		uni.$off("listSelectStateTask");
		EventBus.off("offlineChange", showFinish);
	});

	onShow(() => {
		setTimeout(() => {
			initData();
		}, 0);
	})

	// 初始化数据
	const initData = async () => {
		const network = await checkNetwork(); // 检查网络
		if (network == "none") {
			state.offlineMode = true;
			if (state.isOfflineTipsShow) {
				state.projectType = 5;
				state.isOfflineTipsShow = false;
			}
			uni.removeStorageSync('offline-task-detail');
			let buildList = uni.getStorageSync('offline-task-cache');
			if (buildList && buildList.length) {
				noSign.value = false;
				text.value = '当前处于离线模式，请联网后刷新页面';
				tabList.value = buildList;
				state.list = buildList[state.currentTab].floors.map((item, k) => {
					if (fristAllow.value && item.lockStatus == 1) {
						currentLeft.value = k;
						fristAllow.value = false;
					}
					return {
						...item,
						floorId: item.floorId,
						name: item.floor + 'F',
						subPlanId: item.subPlanId,
					}
				})
				state.floorId = state.list[currentLeft.value].floorId
				getDetails(state.id, state.floorId)
			} else {
				msgToast('暂无缓存');
			}
		} else {
			state.offlineMode = false;
			noSign.value = true;
			checkClock();
		}
		if (uni.getStorageSync('device-C')) searchMethods()
	}

	// 更新列表
	const fatherMethod = () => {
		getDetails(state.id, state.floorId)
	}

	// 显示完成弹窗
	const showFinish = (data) => {
		if (data) {
			let list = uni.getStorageSync("offline-task-list");
			if (!list.isFinish && data.isFinish) {
				list.isFinish = true;
				state.projectType = 3;
				uni.setStorageSync("offline-task-list", list);
			}
		}
	};

	// 检查离线完成情况
	const checkFinish = () => {
		let list = uni.getStorageSync("offline-task-list");
		if (!list.isFinish && !list.offFinish && state.projectType != 5) {
			let statistics = uni.getStorageSync("offline-task-device");
			if (JSON.stringify(statistics) == "{}") {
				state.projectType = 3;
				list.offFinish = true;
				uni.setStorageSync("offline-task-list", list);
			}
		}
	};

	// 定位到设备
	const searchMethods = () => {
		if (uni.getStorageSync('device-C')) {
			let data_ = JSON.parse(uni.getStorageSync('device-C'))
			let index2 = tabList.value.findIndex((i) => i.buildingId == data_.buildingId)
			if (index2 == -1) {
				msgToast('该项目没有该设备');
			} else {
				deviceInfo.value = data_
				state.searchId = deviceInfo.value.deviceId
				changeTab(index2)
				uni.removeStorageSync('device-C')
				state.count = 0
			}
		}
	}

	// 打开提示
	const taskTip = (e) => {
		if (state.offlineMode) {
			msgToast();
			return;
		}
		state.projectType = 2;
		state.unlockParams = e;
	}

	// 解锁
	const setUnlock = (type) => {
		if (type == 2) {
			unlock(state.unlockParams).then(res => {
				if (res.code == 200) {
					msgToast(res.msg);
					setTimeout(() => {
						changeFloor(currentLeft.value)
					}, 1000)
				}
			})
		}
	}

	// 滚动提示
	const getList = () => {
		taskIncomplete(state.id).then((res) => {
			if (res.code == 200) {
				let arr = res.data?.map((i) => {
					return `${i.deviceName || '无'}： 完成 ${i.completedCountSum || 0} 剩余 ${i.totalSum - i.completedCountSum || 0}`
				})
				text.value = arr.join('，')
			}
		})
	}

	// 切换楼层 
	const changeFloor = (e) => {
		rightlist.value = [];
		currentLeft.value = e
		state.count++
		state.floorId = state.list[e].floorId
		if (state.count > 2) {
			state.searchId = ''
		}
		getDetails(state.id, state.floorId)
	}

	// 刷新页面
	const loadDatatList = () => {
		taskSelection(state.id).then((res) => {
			if (res.code == 200) {
				tabList.value = res.data
				state.list = res.data[state.currentTab].floors.map((item) => {
					return {
						...item,
						floorId: item.floorId,
						name: item.floor + 'F',
						subPlanId: item.subPlanId,
					}
				})
			}
		})
		getDetails(state.id, state.floorId)
	}

	// 建筑列表
	const getCompany = () => {
		taskSelection(state.id).then((res) => {
			if (res.code == 200) {
				tabList.value = res.data
				state.list = res.data[state.currentTab].floors.map((item, k) => {
					if (fristAllow.value && item.lockStatus == 1) {
						currentLeft.value = k;
						fristAllow.value = false;
					}
					return {
						...item,
						floorId: item.floorId,
						name: item.floor + 'F',
						subPlanId: item.subPlanId,
					}
				})
				
				let buildList = uni.getStorageSync('offline-task-cache');
				if (buildList && buildList.length) {
					buildList.forEach((build, b) => {
						build.floors.forEach((floor, f) => {
							floor.isFinish = res.data[b]?.floors[f]?.isFinish || false;
						})
					})
					uni.setStorageSync('offline-task-cache', buildList)
				}
				// if (state.list.every(i => i.isFinish)) {
				// 	state.projectType = 3;
				// }
				state.floorId = state.list[currentLeft.value].floorId
				getDetails(state.id, state.floorId)
			}
		})
	}

	// 系统列表
	const getDetails = (a, b) => {
		uni.setStorageSync('clock-ID', state.id)
		uni.setStorageSync('clock-FloorID', state.floorId)
		if (state.offlineMode) {
			rightlist.value = tabList.value[state.currentTab].floors[currentLeft.value].systemDtoList || []
			uni.setStorageSync('offline-task-build', {
				buildingName: tabList.value[state.currentTab].buildingName,
				buildingId: tabList.value[state.currentTab].buildingId,
				floor: tabList.value[state.currentTab].floors[currentLeft.value].floor,
				floorId: tabList.value[state.currentTab].floors[currentLeft.value].floorId,
			})
			checkFinish();
		} else {
			taskSystem(a, b).then((res) => {
				if (res.code == 200) {
					rightlist.value = res.data
					// #ifdef APP-PLUS
					let buildList = uni.getStorageSync('offline-task-cache');
					if (buildList && buildList.length) {
						let list = buildList[state.currentTab].floors[currentLeft.value].systemDtoList || [];
						let isFinish = true; // 是否全部完成
						list.forEach((item, index) => {
							let row = res.data[index];
							item.total = row.total;
							item.deviceRemainTotal = row.deviceRemainTotal;
							item.completedCount = row.completedCount;
							item.finishedRate = row.finishedRate;
							item.passStatus = row.passStatus;
							item.lockStatus = row.lockStatus;
							if (row.completedCount < row.total && row.total != 0) {
								isFinish = false;
							}
							item.deviceTasksList.forEach((item2, index2) => {
								let row2 = res.data[index].deviceTasksList[index2];
								item2.total = row2.total;
								item2.deviceRemainTotal = row2.deviceRemainTotal;
								item2.completedCount = row2.completedCount;
								item2.passStatus = row2.passStatus;
								item2.lockStatus = row2.lockStatus;
								item2.tasksItemList.forEach((item3, index3) => {
									let row3 = res.data[index].deviceTasksList[index2].tasksItemList[index3];
									item3.total = row3.total;
									item3.deviceRemainTotal = row3.deviceRemainTotal;
									item3.completedCount = row3.completedCount;
									item3.finishedRate = row3.finishedRate;
									item3.passStatus = row3.passStatus;
								})
							})
						})
						buildList[state.currentTab].floors[currentLeft.value].isFinish = isFinish;
						buildList[state.currentTab].floors[currentLeft.value].systemDtoList = list;
						uni.setStorageSync('offline-task-cache', buildList)
					}
					// #endif
				}
			})
		}
	}

	const GetWxMiniProgramUrlParam = (url) => {
		let theRequest = {};
		if (url.indexOf("#") != -1) {
			const str = url.split("#")[1];
			const strs = str.split("&");
			for (let i = 0; i < strs.length; i++) {
				theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
			}
		} else if (url.indexOf("?") != -1) {
			const str = url.split("?")[1];
			const strs = str.split("&");
			for (let i = 0; i < strs.length; i++) {
				theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
			}
		}
		return theRequest;
	}

	// 扫码
	const handleScan = () => {
		if (state.offlineMode) {
			msgToast();
			return;
		}
		uni.scanCode({
			success: (res) => {
				if (res.result && res.result != "undefined") { //扫码进入
					const qrUrl = decodeURIComponent(res.result) // 获取到二维码原始链接内容
					state.t = GetWxMiniProgramUrlParam(qrUrl); //此处就是我们要获取的参数 json
				}
				let arr = JSON.parse(res.result)
				uni.setStorageSync('device-C', JSON.stringify(arr))
				searchMethods()
				console.log('条码：' + res.result);
				console.log('解析后：' + JSON.stringify(state.t));
			}
		});
	}

	// 跳转离线任务
	const handleOffline = () => {
		state.twoCode = false;
		uni.navigateTo({
			url: `/pages/Task/offlineTask?subPlanId=${state.id}`
		})
	}

	// 显示按钮
	const showCode = () => {
		state.twoCode = !state.twoCode
		rotating.value = true;
		setTimeout(() => {
			rotating.value = false;
		}, 400);
	}

	// 查看详情
	const Jump = () => {
		if (state.offlineMode) {
			msgToast();
			return;
		}
		uni.navigateTo({
			url: `/pages/Task/findDetails?id=${state.id}`
		})
	}
	// 切换建筑
	const changeTab = (index) => {
		state.currentTab = index
		fristAllow.value = true;
		currentLeft.value = 0;
		state.list = tabList.value[index].floors.map((item, k) => {
			if (fristAllow.value && item.lockStatus == 1) {
				currentLeft.value = k;
				fristAllow.value = false;
			}
			return {
				...item,
				floorId: item.floorId,
				name: item.floor + 'F',
				subPlanId: item.subPlanId,
				isSearch: true
			}
		})
		// if (state.list.every(i => i.isFinish)) {
		// 	state.projectType = 3;
		// }
		if (state.list.findIndex(i => i.floorId == deviceInfo.value.floorId) > -1) {
			let index = state.list.findIndex((i) => i.floorId == deviceInfo.value.floorId)
			nextTick(() => {
				changeFloor(index)
			})
		} else {
			changeFloor(currentLeft.value)
		}

	}
	// 检测是否打卡 
	const checkClock = async () => {
		if (!noSign.value) return
		let res = await isClockIn(state.id)
		if (res.code == 200) {
			if (res.data) {
				noSign.value = false;
				getCompany()
				getList()
			} else {
				noSign.value = true;
			}
		}
	};

	// 返回上一页
	const handleBack = () => {
		uni.navigateBack({
			delta: 1
		})
	}

	// 提示
	const msgToast = (title = '离线模式无法操作') => {
		uni.showToast({
			title,
			icon: 'none',
		})
	}

	// 去打卡
	const handleToSign = () => {
		if (state.offlineMode) {
			msgToast();
			return;
		}
		uni.navigateTo({
			url: `/pages/sign/index?subPlanId=${state.id}`,
			success: () => {
				// noSign.value = false;
				state.twoCode = false;
			}
		});
	};
</script>
<style lang="scss" scoped>
	@import '@/uni.scss';

	.list {
		width: 100%;
		margin: 0;

		.toDetail {
			width: 26.8%;
		}

		.list_tit {
			margin-top: 40rpx;
			box-shadow: 0rpx 0rpx 40rpx 4rpx #d4fce3;
			background-image: linear-gradient(to right, #4EA770, #7ebc8e, #8ce0ad);
			border-top-left-radius: 20rpx;
			border-top-right-radius: 20rpx;
		}

		.tabBox {
			display: flex;
			justify-content: space-between;
			background-color: #fff;
			width: 100%;
			padding: 10rpx 20rpx 0;
			box-sizing: border-box;
			text-align: left;
			font-size: 30rpx;
			overflow-x: auto;
			border: 2rpx solid #fff;
			border-bottom: 2rpx solid #E6F1E9;
			background-image: linear-gradient(to bottom, #f1fff6, #fff);
			border-top-left-radius: 20rpx;
			border-top-right-radius: 20rpx;
			box-shadow: 0 -10rpx 20rpx 2rpx rgba(78, 167, 112, 0.16);

			.tab_list {
				min-width: 80rpx;
				padding: 0 36rpx;
				text-align: center !important;
			}
		}
	}

	:deep() .uv-scroll-list {
		padding-bottom: 0 !important;
	}

	:deep() {
		.uv-radio {
			border: 2rpx solid #DCDFE6;
			padding: 20rpx 50rpx;
			border-radius: 10rpx;
			margin: 20rpx 30rpx;
		}
	}

	.more-box {
		position: fixed;
		right: 30rpx;
		bottom: 60rpx;
		z-index: 990;

		.more-btn {
			width: 92rpx;
			height: 92rpx;
			border-radius: 46rpx;
			background-color: #4EA770;
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 992;
			position: relative;
			&:active {
				background-color: rgb(90, 195, 130);
			}
		}

		.rotating {
			transform: rotate(180deg);
			transition: all 0.4s;
		}

		.icon_left {
			display: flex;
			align-items: center;
			background: #fff;
			height: 100%;
			position: absolute;
			right: 0;
			top: 0;
			z-index: 991;
			overflow: hidden;
			box-shadow: 0 0 20rpx 2rpx rgba(120, 120, 120, 0.16);
			border-radius: 46rpx;
			transition: all 0.5s;
			.icon_line {
				width: 2rpx;
				height: 50rpx;
				background: #E6F1E9;
			}
		}
	}

	:deep(.uv-icon__label) {
		white-space: nowrap;
	}

	.no-sign {
		position: fixed;
		left: 0;
		bottom: 0;
		right: 0;
		top: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 1000;
		backdrop-filter: blur(20rpx);
		transition: all 3s;

		.sign-box {
			width: 598rpx;
			background: #FFFFFF;
			box-shadow: 0 6rpx 12rpx 2rpx rgba(0, 0, 0, 0.16);
			border-radius: 24rpx;
			overflow: hidden;

			.sign-top {
				padding: 60rpx;
				display: flex;
				justify-content: center;
				flex-direction: column;
				align-items: center;
				border-bottom: 2rpx solid #E5E5E5;

				image {
					width: 68rpx;
					height: 80rpx;
				}
			}

			.sign-bottom {
				height: 80rpx;
				display: flex;
				align-items: center;

				.sign-btn {
					flex: 1;
					line-height: 80rpx;
					color: #333333;
					font-size: 32rpx;
					text-align: center;
					border-right: 2rpx solid #E5E5E5;

					&:active {
						background: #E5E5E5;
					}
				}
			}
		}
	}
</style>